package com.lvyq.javaprint.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

/**
 * @description  代理转发+响应本地静态资源
 * @author lvyq
 * @param[1] null
 * @throws

 * @time 2024-08-09 17:20
 */
@Controller
public class ProxyController {

    @Value("${proxy.target.url}")
    private String targetUrl;

    private final RestTemplate restTemplate = new RestTemplate();

    @RequestMapping(value = "/**", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.PATCH})
    @ResponseBody
    public ResponseEntity<byte[]> proxy(HttpMethod method,
                                        @RequestHeader MultiValueMap<String, String> headers,
                                        @RequestBody(required = false) byte[] body,
                                        HttpServletRequest request) {
        String proxyUrl = targetUrl + request.getRequestURI();
        System.out.println("proxyUrl = " + proxyUrl);
        HttpEntity<byte[]> entity = new HttpEntity<>(body, headers);
        ResponseEntity<byte[]> response = restTemplate.exchange(proxyUrl, method, entity, byte[].class);
        return ResponseEntity
                .status(response.getStatusCode())
                .headers(response.getHeaders())
                .body(response.getBody());
    }


    /**
     * @description 委托模版资源
     * @author lvyq
     * @param[1] filename
     * @throws
     * @return String
     * @time 2024-08-13 10:54
     */
    @GetMapping("/powerAttorney/{filename}")
    @ResponseBody
    public String readFile(@PathVariable("filename") String filename) throws IOException {
       // ClassPathResource resource = new ClassPathResource("public/powerAttorney/" +filename);
        // 读取文件内容并转换为字符串
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(getInputStream("public/powerAttorney/" +filename), StandardCharsets.UTF_8))) {
            return reader.lines().collect(Collectors.joining("\n"));
        }
    }

    /**
     * @description 报告模版资源
     * @author lvyq
     * @param[1] filename
     * @throws
     * @return String
     * @time 2024-08-14 9:25
     */
    @GetMapping("/report/{filename}")
    @ResponseBody
    public String readReport(@PathVariable("filename") String filename) throws IOException {

       // ClassPathResource resource = new ClassPathResource("public/report/" +filename);
        // 读取文件内容并转换为字符串
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(getInputStream("public/report/" + filename), StandardCharsets.UTF_8))) {
            return reader.lines().collect(Collectors.joining("\n"));
        }
    }


    @GetMapping("/originalRecords/{filename}")
    @ResponseBody
    public String readOriginalRecords(@PathVariable("filename") String filename) throws IOException {

      //  ClassPathResource resource = new ClassPathResource("public/originalRecords/" +filename);
        // 读取文件内容并转换为字符串
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(getInputStream("public/originalRecords/" +filename), StandardCharsets.UTF_8))) {
            return reader.lines().collect(Collectors.joining("\n"));
        }
    }



    @GetMapping("/fonts/{filename}")
    public ResponseEntity<Object> getFile(@PathVariable("filename")  String filename) {
        HttpHeaders headers = new HttpHeaders();
        if (filename.endsWith("ttf")){
            byte[] fileContent = new byte[0];
            try {
                fileContent = getInputStream("public/fonts/" +filename).readAllBytes();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
          //  headers.setContentType(MediaType.valueOf("font/ttf"));
            headers.setContentType(MediaType.valueOf("application/octet-stream"));
            headers.setContentLength(fileContent.length);
            return new ResponseEntity<>(fileContent, headers, HttpStatus.OK);
        }else {
            String reader="{\"path\":\"\",\"descriptors\":[{\"name\":\"微软雅黑\",\"source\":\"../fonts/SimHei.ttf\"},{\"name\":\"宋体\",\"source\":\"../fonts/song.ttf\"},{\"name\":\"黑体\",\"source\":\"../fonts/SimHei.ttf\"}]}";
            return new ResponseEntity<>(reader, headers, HttpStatus.OK);

        }
    }

    /**
     * @description 获取流
     * @author lvyq
     * @param[1] path
     * @throws
     * @return InputStream
     * @time 2024-08-15 14:19
     */
   public InputStream getInputStream(String path) throws FileNotFoundException {
       String property = System.getProperty("user.dir");
       property=property+"\\"+path;
       System.out.println("property = " + property);
       File file = new File(property);
       InputStream inputStream= new FileInputStream(file);
       return inputStream;
   }
}
